<template>
<div class="header">
    <img :src="currentShopInfo.shopImage">
    <p style="color: white">{{currentShopInfo.shopName}}</p>
    <el-button type="primary" round @click="getMyItems()">我的商品</el-button>
</div>
    <h5>商品列表</h5>
  <ul style="width: 100%">
      <li class="item"  v-for="item in shopItemList">
          <div style="height: 100%" class="itemInfo">
              <img style="height: 100%" :src="item.itemImg" alt="">
              <div class="item-details">
                  <h4>
                      {{item.itemName}}
                      <el-tag class="ml-3" :type="item.isOnShelves === 1?'danger':'success'">{{ item.isOnShelves === 1?'已下架':'已上架' }}</el-tag>
                  </h4>
                  <p style="margin: 0">{{item.itemDescription}}</p>
                  <p style="margin: 0">{{item.shopItemPrice}}￥</p>
              </div>
          </div>
          <el-button @click="changeState(item.id)" :type="item.isOnShelves === 1?'success':'danger'" size="small" round >{{item.isOnShelves === 1?'上架商品':'下架商品'}}</el-button>
      </li>
  </ul>

  <!--    下面是添加门店弹出框-->
    <el-dialog v-model="dialogFormVisible" title="添加商品" width="90%">
        <el-form :model="form">
            <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input v-model="form.itemName" autocomplete="off" />
            </el-form-item>

            <el-form-item label="商品价格" :label-width="formLabelWidth">
                <el-input v-model="form.itemPrice" autocomplete="off" />
            </el-form-item>

            <el-form-item label="商品描述" :label-width="formLabelWidth">
                <el-input
                        v-model="form.itemDescription"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"
                        placeholder="Please input"
                />
            </el-form-item>
            <el-form-item>
                <el-upload
                        class="upload-demo"
                        :on-change="handlePreview"
                        list-type="picture"
                        :auto-upload="false"
                        :limit="1"
                >
                    <el-button type="primary">添加商品图片</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submit">
          提交
        </el-button>
      </span>
        </template>
    </el-dialog>
<!--    下面是全部商品的测边框-->
    <el-drawer v-model="drawer" title="商品列表" size="50%">
        <el-button type="primary" size="small" round @click="dialogFormVisible = true">添加商品</el-button>
        <ul style="width: 100%">
            <li class="item" style="flex-direction: column;justify-content: space-around;height: 50vw" v-for="item in itemList">
                <div style="height: 50%;flex-direction: column;" class="itemInfo" >
                    <img style="height: 80%" :src="item.itemImg" alt="">
                    <div class="item-details">
                        <h4 style="margin: 0">
                            {{item.itemName}}
                        </h4>
                        <p style="margin: 0">{{item.itemDescription}}</p>
                        <p style="margin: 0">{{item.itemPrice}}￥</p>
                    </div>
                </div>
                <el-button size="small" :type="item.isOnShelves?'success':''"  @click="setShopItem(item)">{{item.isOnShelves?'已上架':'上架'}}</el-button>
            </li>
        </ul>
    </el-drawer>
    <!--    下面是上架商品弹出框-->
    <el-dialog v-model="priceFormVisible" title="设置" width="90%">
        <el-form :model="shopItemForm">
            <el-form-item label="商品编号" :label-width="formLabelWidth">
                <el-input v-model="shopItemForm.id" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-input v-model="shopItemForm.itemName" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="上架价格" :label-width="formLabelWidth">
                <el-input-number v-model="shopItemForm.itemPrice" :min="1" autocomplete="off"/>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="createShopItem()">
          上架
        </el-button>
      </span>
        </template>
    </el-dialog>
</template>

<script setup>
import {useRoute} from "vue-router";
import {onMounted, reactive, ref} from "vue";
import {
    getShopByIdAPI,
    updateShopItemStateAPI,
    listMyItemsAPI,
    createItemAPI,
    createShopItemAPI,
    listMyShopItemsAPI
} from "../api/api.js";
import {getSessionStorage} from "../common.js";
const route = useRoute()
const drawer = ref(false)

const currentShopInfo = ref({})
const shopItemList = reactive([])
const itemList  =reactive([])
const formLabelWidth = '100px'
const user = getSessionStorage("user")
const dialogFormVisible = ref(false)
const priceFormVisible  = ref(false)
const getMyItems = async ()=>{
    //获取全部商品
    drawer.value = true
    await listMyItemsAPI(user.token).then(res=>{
        itemList.splice(0,itemList.length)
        itemList.push(...res.data.data.map(item => {
            const isOnShelves = shopItemList.some(shopItem => shopItem.itemId === item.id);
            return { ...item, isOnShelves: isOnShelves };
        }))
    })
}
const setShopItem = (item)=>{
    priceFormVisible.value = true
    shopItemForm = item
}
const form = reactive({
    itemName: '',
    itemDescription:"",
    itemPrice:"",
    itemImg:"",
})
let shopItemForm = reactive({
})
const handlePreview = (e)=>{
    const file = e.raw
    // 创建 FileReader 对象
    const reader = new FileReader();

    // 读取文件内容，将其转换为 Base64 编码
    reader.onload = function(event) {
        form.itemImg = event.target.result
    };

    reader.readAsDataURL(file);
}

const submit = async ()=>{
    await createItemAPI(user.token,form).then(res=>{
        if (res.data.data.id>0){
            alert("添加成功！")
            dialogFormVisible.value = false
            Object.keys(form).forEach(key => {
                form[key] = null;
            });
        }else {
            console.log("添加失败")
        }
    }).catch(e=>console.log(e))
    // await getShopItemByShopAPI(getSessionStorage("user").token,route.params.shopId).then(res=>{
    //     shopItemList.splice(0,shopItemList.length)
    //     shopItemList.push(...res.data)
    // })
    await listMyItemsAPI(user.token).then(res=>{
        itemList.splice(0,itemList.length)
        itemList.push(...res.data.data)
    })
}

onMounted(async ()=>{
    const shopData = new FormData()
    shopData.append("id",route.params.shopId)

    await getShopByIdAPI(user.token,shopData).then(res=>{
        currentShopInfo.value = res.data.data
    }).catch(e=>console.log(e))

    await listMyShopItemsAPI(user.token,route.params.shopId).then(res=>{
        shopItemList.splice(0,shopItemList.length)
        shopItemList.push(...res.data.data)
    })

})
const createShopItem = async ()=>{
    if (!shopItemForm.isOnShelves){
        const shopItemData = new FormData()
        shopItemData.append("itemId",shopItemForm.id)
        shopItemData.append("shopId",route.params.shopId)
        shopItemData.append("price",shopItemForm.itemPrice)

        await createShopItemAPI(user.token,shopItemData).then(res=>{
            if (res.data.data){
                alert("上架成功")
            }else {
                alert("上架失败")
            }
        }).finally(()=>{
            priceFormVisible.value = false
        })
        await listMyShopItemsAPI(user.token,route.params.shopId).then(res=>{
            shopItemList.splice(0,shopItemList.length)
            shopItemList.push(...res.data.data)
        })
    }else {
        alert("商品已经上架")
    }


}
const changeState = (shopItemId)=>{
    const data = new FormData()
    data.append("shopId",route.params.shopId)
    data.append("shopItemId",shopItemId)

    updateShopItemStateAPI(user.token,data).then(res=>{
        console.log(res.data.data)
        if (res.data.code === "200"){
            const index = shopItemList.findIndex(shopItem=>shopItem.id === res.data.data.id)
            shopItemList[index] = res.data.data
            alert("修改成功")
        }else {
            alert("修改失败")
        }
    }).catch(e=>console.log(e))
}

</script>

<style scoped>
.header{
    width: 99%;
    height: 250px;
    background-color: #70ceef;

    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.item{
    width: 95%;
    height: 25vw;
    margin-bottom: 1.2vw;
    border: 1px solid #d7cfcf;
    display: flex;
    align-items: center;
    justify-content: space-between;

    padding-left: 1.2vw;
    padding-right: 2.2vw;
}

.itemInfo{
    display: flex;
    align-items: center;
    justify-content: center;

}
.item .itemInfo .item-details h4{
    font-size: 3.8vw;
    color: #555;
    text-align: left;
}
.item .itemInfo .item-details p{
    font-size: 3vw;
    color: #888;
    margin-top: 2vw;
    text-align: left;
}
</style>